package com.am.mosl.cityandroid.mainboard;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.am.mosl.cityandroid.leftmenu.JoinActivity;
import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.activity.BaseActivity;
import com.am.mosl.cityandroid.bean.Ad;
import com.am.mosl.cityandroid.bean.ArticleDetail;
import com.am.mosl.cityandroid.constant.HttpConstant;
import com.am.mosl.cityandroid.thirdshare.Constants;
import com.am.mosl.cityandroid.util.DeviceUtil;
import com.am.mosl.cityandroid.util.ImageTools;
import com.am.mosl.cityandroid.widget.MyWebView;
import com.am.mosl.cityandroid.widget.SharePopWindow;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.share.IWeiboDownloadListener;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * Created by mosl on 14-7-1. 文章详情
 */
public class ActivityDetailActivity extends BaseActivity implements
		View.OnClickListener {

	public static final String TAG = "ActivityDetailActivity";
	public static final String Intent_To_ArticleDetail = "Intent_To_ArticleDetail";

	private String mArticleId = null;
	private SharePopWindow sharePopWindow;

	private View mIWantTo;
	private Ad mAd;
	private MyWebView contentView;
	private String mCityId;
	private View mAdLayout;
	private ShareData data;

	private Bitmap bitmap;
	private int CountMessage = 0;

	private android.os.Handler handler = new android.os.Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			CountMessage++;
			if (CountMessage == 3) {
				EventBus.getDefault().post(new LoadingMessage(1));
				ad_layout.setVisibility(View.VISIBLE);
				data.bitmap = bitmap;
			}
		}
	};

	private IWXAPI api;
	private IWeiboShareAPI mWeiboShareAPI = null;

	Tencent tencent;

	private ArticleDetail articleDetail;

	TextView people;

	private View ad_layout;

	class PicTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			bitmap = GetLocalOrNetBitmap(params[0]);
			return null;
		}

		@Override
		protected void onPostExecute(Void aVoid) {
			super.onPostExecute(aVoid);
			handler.sendEmptyMessage(1);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		contentView.setWebChromeClient(new WebChromeClient());
		contentView.getSettings().setPluginState(
				WebSettings.PluginState.ON_DEMAND);
		contentView.getSettings().setJavaScriptEnabled(true);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(JoinActivity.JoinMessage.class);
	}

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		//startActivity(new Intent(this, LoadingActivity.class));
		setContentView(R.layout.activity_detail_layout);
		api = WXAPIFactory.createWXAPI(this, Constants.WeiX_APP_ID, false);
		api.registerApp(Constants.WeiX_APP_ID);
		tencent = Tencent.createInstance(Constants.Tencent_AppId,
				ActivityDetailActivity.this);
		ad_layout = findViewById(R.id.ad_layout);
		people = (TextView) findViewById(R.id.people);
		Intent intent = getIntent();
		mArticleId = intent.getStringExtra(Intent_To_ArticleDetail);
		data = (ShareData) intent.getExtras().getSerializable("data");
		data.url = HttpConstant.GetArticleDetailHttp + mArticleId;
		mCityId = intent.getStringExtra("cityId");
		if (mArticleId == null) {
			onBackPressed();
		}
		final TextView share = (TextView) findViewById(R.id.share);
		share.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				sharePopWindow = new SharePopWindow(
						ActivityDetailActivity.this, itemsOnClick, callBack);
				sharePopWindow.showAtLocation(
						ActivityDetailActivity.this.findViewById(R.id.mainmenu),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});
		initWebViews();
		mIWantTo = (View) findViewById(R.id.i_want_to);
		mIWantTo.setOnClickListener(this);
		mAdLayout = findViewById(R.id.ad_layout);
		initActionBar();
		GetAdvertisement(mCityId);
		new PicTask().execute(data.imageUrl);
		GetArticleDetail();

		EventBus.getDefault().register(this, "joinSuccess",
				JoinActivity.JoinMessage.class);
	}

	private void joinSuccess(JoinActivity.JoinMessage message) {
		GetArticleDetail();
		people.setText(articleDetail.getHasregistion());
	}

	private void GetArticleDetail() {
		FinalHttp finalHttp = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("contentid", mArticleId);
		finalHttp.post(HttpConstant.ArticleDetail, params,
				new AjaxCallBack<Object>() {
					@Override
					public void onSuccess(Object o) {

						try {
							JSONObject jsonObject = new JSONObject(o.toString());
							String status = (String) jsonObject.opt("status");
							if (status.endsWith("1")) {
								JSONObject object = (JSONObject) jsonObject
										.opt("data");
								articleDetail = JSON.parseObject(
										object.toString(), ArticleDetail.class);
								if (articleDetail.getIsparty() == 1) {
									findViewById(R.id.party).setVisibility(
											View.VISIBLE);

									people.setText("共有"
											+ articleDetail.getHasregistion()
											+ "人报名");
								}

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

						super.onSuccess(o);
					}
				});
	}

	private void initActionBar() {

		View back = (View) findViewById(R.id.framelayout_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ActivityDetailActivity.this.onBackPressed();
			}
		});

	}

	@SuppressLint("NewApi")
	@Override
	protected void onPause() {
		super.onPause();
		contentView.onPause();
	}

	private void initWebViews() {

		contentView = (MyWebView) findViewById(R.id.wv);
		contentView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				handler.sendEmptyMessage(1);
			}
		});

		contentView.loadUrl(data.url+"&isapp=1");
		contentView
				.setOnCustomScroolChangeListener(new MyWebView.ScrollInterface() {
					@Override
					public void onSChanged(int l, int t, int oldl, int oldt) {
						Log.e("Value",
								(contentView.getContentHeight()
										* contentView.getScale() - (contentView
										.getHeight() + contentView.getScrollY()))
										+ "");
						if (contentView.getContentHeight()
								* contentView.getScale()
								- (contentView.getHeight() + contentView
										.getScrollY()) == 0) {
							// 已经处于底端
							Log.d("Value", "is bottom");
						}
					}

				});

	}

	// 为弹出窗口实现监听类
	private View.OnClickListener itemsOnClick = new View.OnClickListener() {
		public void onClick(View v) {
			Log.d(TAG, "dismiss");

			sharePopWindow.dismiss();
		}

	};

	@Override
	public void onClick(View v) {

	}

	public void baoming(View view) {
		Intent intent = new Intent(ActivityDetailActivity.this,
				JoinActivity.class);
		if (mArticleId != null) {
			intent.putExtra("contentId", mArticleId);
			startActivity(intent);
		}

	}

	public static Bitmap GetLocalOrNetBitmap(String url) {
		Bitmap bitmap = null;
		InputStream in = null;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(new URL(url).openStream(), 1024);
			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			out = new BufferedOutputStream(dataStream, 1024);
			copy(in, out);
			out.flush();
			byte[] data = dataStream.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			data = null;
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

	public final void GetAdvertisement(String cityId) {
		AjaxParams params = new AjaxParams();
		if (MainActivity.mCityId != -1)
			cityId = MainActivity.mCityId + "";
		params.put("cityid", cityId);
		FinalHttp finalHttp = new FinalHttp();
		finalHttp.post(HttpConstant.AdvertisementHttp, params,
				new AjaxCallBack<Object>() {
					@Override
					public boolean isProgress() {
						return super.isProgress();
					}

					@Override
					public void onSuccess(Object o) {
						super.onSuccess(o);
						try {
							JSONObject jsonObject = new JSONObject(o.toString());
							Log.d("Hello", jsonObject.toString());
							String status = (String) jsonObject.opt("status");
							if (status.endsWith("1")) {
								JSONObject object = (JSONObject) jsonObject
										.opt("data");
								Log.d(TAG, object.toString());
								mAd = JSON.parseObject(object.toString(),
										Ad.class);
								final ImageView image = (ImageView) findViewById(R.id.acticity_ad);
								if (mAd != null)
									ImageLoader.getInstance().loadImage(
											ActivityDetailActivity.this,
											mAd.getImage(),
											new ImageLoadingListener() {

												@Override
												public void onLoadingStarted() {
													// TODO Auto-generated
													// method stub

												}

												@Override
												public void onLoadingFailed(
														FailReason arg0) {
													// TODO Auto-generated
													// method stub

												}

												@Override
												public void onLoadingComplete(
														Bitmap arg0) {
													// TODO Auto-generated
													// method stub
													float bili = 1.0f
															* arg0.getHeight()
															/ arg0.getWidth();
													Log.i("zcc", "比例" + bili);

													int screem_width = DeviceUtil
															.getWindowWidth(ActivityDetailActivity.this);
													int imageView_width = screem_width
															- 2
															* DeviceUtil
																	.dip2px(ActivityDetailActivity.this,
																			10);
													LayoutParams lp = (LayoutParams) image
															.getLayoutParams();
													Log.i("zcc", "imageview宽度"
															+ imageView_width);
													lp.weight = imageView_width;
													lp.height = (int) (imageView_width * bili);
													Log.i("zcc", "view高"
															+ lp.height);

													image.setLayoutParams(lp);
													image.setImageBitmap(arg0);
													handler.sendEmptyMessage(1);
												}

												@Override
												public void onLoadingCancelled() {
													// TODO Auto-generated
													// method stub

												}
											});
								// ImageLoader.getInstance().displayImage(
								// mAd.getImage(), image);
								// image.setDrawingCacheEnabled(true);
								image.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										intent.setData(Uri.parse(mAd.getLink()));
										startActivity(intent);
									}
								});
								// Bitmap b =image.getDrawingCache();
								// b.getHeight();

							}

							if (status.endsWith("0")) {
								mAdLayout.setVisibility(View.INVISIBLE);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	private SharePopWindow.ShareCallBack callBack = new SharePopWindow.ShareCallBack() {
		@Override
		public void share(int type) {

			switch (type) {
			case 0: // 新浪微博
				shareToWeiBo(data);
				break;
			case 1:
				shareToQzone();
				break;
			case 2:
				shareToWex(data, 0);
				break;
			case 3:
				shareToWex(data, 1);
				break;

			}
		}
	};

	private void shareToWeiBo(ShareData data) {

		mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(
				ActivityDetailActivity.this, Constants.WeiBo_APP_ID);
		// 页面初始化时注册
		boolean flag = mWeiboShareAPI.registerApp();
		Log.i("zcc", flag + "");
		// 如果未安装微博客户端，设置下载微博对应的回调
		if (!mWeiboShareAPI.isWeiboAppInstalled()) {
			mWeiboShareAPI
					.registerWeiboDownloadListener(new IWeiboDownloadListener() {
						@Override
						public void onCancel() {
							Toast.makeText(ActivityDetailActivity.this, "下载失败",
									Toast.LENGTH_SHORT).show();
						}
					});
		}
		// 检查微博是否安装，没安装弹框
		if (mWeiboShareAPI.checkEnvironment(true)) {
			if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
				// 1. 初始化微博的分享消息
				// 用户可以分享文本、图片、网页、音乐、视频中的一种
				WeiboMessage weiboMessage = new WeiboMessage();

				WebpageObject mediaObject = new WebpageObject();
                Log.i("zcc", Utility.generateGUID()+data.title+data.des);
				mediaObject.identify = Utility.generateGUID();
				mediaObject.title = data.title;
				mediaObject.description = data.des;
				if (data.bitmap != null) {
					Bitmap newBitmap = ImageTools.zoomBitmap(data.bitmap,
							DeviceUtil.dip2px(ActivityDetailActivity.this, 80),
							DeviceUtil.dip2px(ActivityDetailActivity.this, 60));
					mediaObject.setThumbImage(newBitmap);
				}
				mediaObject.actionUrl =data.url;
				mediaObject.defaultText = data.title;

				weiboMessage.mediaObject = mediaObject;

				// 2. 初始化从第三方到微博的消息请求
				SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
				// 用transaction唯一标识一个请求
				request.transaction = String
						.valueOf(System.currentTimeMillis());
				request.message = weiboMessage;

				Log.i("zcc", "发送微博");
				// 3. 发送请求消息到微博，唤起微博分享界面
				Log.i("zcc", "微博返回的信息" + mWeiboShareAPI.sendRequest(request));
			} else {
				Toast.makeText(this, "出错啦", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void shareToWex(ShareData data, int type) {

		WXWebpageObject webpage = new WXWebpageObject();

		if (data.url != null)
			webpage.webpageUrl = data.url;
		WXMediaMessage msg = new WXMediaMessage(webpage);

		if (data.title == null) {
			msg.title = "百城通";
		} else {
			msg.title = data.title;
		}

		if (data.des != null)
			msg.description = data.des;

		if (data.bitmap != null) {
			Bitmap newBitmap = ImageTools.zoomBitmap(data.bitmap,
					DeviceUtil.dip2px(ActivityDetailActivity.this, 80),
					DeviceUtil.dip2px(ActivityDetailActivity.this, 60));
			msg.thumbData = Util.bmpToByteArray(newBitmap, true);
		}

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		switch (type) {
		case 0: // 分享到微信
			req.scene = SendMessageToWX.Req.WXSceneSession;
			break;
		case 1: // 分享到朋友圈
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
		}
		api.sendReq(req);

	}

	private void shareToQzone() {
		Bundle params = new Bundle();
		params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
				QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		String title = data.title;
		if (title == null) {
			title = "百城通";
		}
		params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 必填
		params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, data.url);// 必填
		params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "百城通");// 必填
		String summery = data.des;
		if (summery == null) {
			summery = "百城通";
		}
		params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summery);
		ArrayList<String> imageUrls = new ArrayList<String>();
		imageUrls.add(data.imageUrl);
		params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
		shareToQZoneInThread(params);
	}

	private void shareToQZoneInThread(final Bundle params) {
		Log.d("hello", "share to zone ");
		final Activity activity = ActivityDetailActivity.this;
		new Thread(new Runnable() {
			@Override
			public void run() {
				tencent.shareToQzone(activity, params, new IUiListener() {

					@Override
					public void onCancel() {
						// Util.toastMessage(activity, "onCancel: ");
						Log.d("hello", "onCancel");
					}

					@Override
					public void onError(UiError e) {
						// TODO Auto-generated method stub
						// Util.toastMessage(activity, "onError: " +
						// e.errorMessage, "e");
						Log.d("hello", "onError" + e.errorMessage);
					}

					@Override
					public void onComplete(Object response) {
						// TODO Auto-generated method stub
						// Util.toastMessage(activity, "onComplete: " +
						// response.toString());
						Log.d("hello", "onComplete" + response.toString());
					}

				});
			}
		}).start();

	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	public static class ShareData implements Serializable {

		public String title;
		public Bitmap bitmap;
		public String url;
		public String des;
		public String imageUrl;
	}

}